package props

import (
	"strings"

	"gitee.com/night-tc/gen-entity/gencode"
	"gitee.com/night-tc/gobige/msgdef"
	"gitee.com/night-tc/gobige/msgdef/protomsg"
)

/*
服务中进行属性同步的模块
它可以用与服务器之间的属性同步
也可以同步到客户端
然后服务器间的数据管理也是基于它进行的
*/

// 自动生成的属性包装代码实现的接口
type IDef interface {
	SetPropDirtyMgr(pmgr *PropDirtyMgr)
}

const (
	PackProp_Role uint8 = 1
	PackProp_AOI  uint8 = 2
)

// 加载entity的jsonc配置
func LoadDef(filePath string) (*Def, error) {
	if strings.HasSuffix(filePath, ".jsonc") {
		nttdata, err := gencode.LoadEntity(filePath)
		if err != nil {
			return nil, ErrDef_FileNotFound.NewErr(err)
		}

		def := newDef()
		if err := def.fill(nttdata); err != nil {
			return nil, ErrDef_Fill.NewErr(err)
		}

		return def, nil
	}

	return nil, nil
}

// PackPropsToProtobuf 把属列表打包成proto
func PackPropsToProtobuf(props []IProp) (result []*protomsg.SyncProp) {

	if len(props) == 0 {
		return nil
	}
	result = make([]*protomsg.SyncProp, len(props))
	for i, prop := range props {
		msg := new(protomsg.SyncProp)
		// baseMsg := &protoMsg.SyncBaseInfo{
		// 	PropValue: &protoMsg.SyncBaseInfo_BoolValue{},
		// }
		msg.Index = uint32(prop.GetField().Index)
		switch v := prop.GetValue().(type) {
		case bool:
			msg.PropValue = &protomsg.SyncProp_BoolValue{
				BoolValue: v,
			}
		case int8:
			msg.PropValue = &protomsg.SyncProp_Int32Value{
				Int32Value: int32(v),
			}
		case int16:
			msg.PropValue = &protomsg.SyncProp_Int32Value{
				Int32Value: int32(v),
			}
		case int32:
			msg.PropValue = &protomsg.SyncProp_Int32Value{
				Int32Value: v,
			}
		case int64:
			msg.PropValue = &protomsg.SyncProp_Int64Value{
				Int64Value: v,
			}
		case uint8:
			msg.PropValue = &protomsg.SyncProp_Uint32Value{
				Uint32Value: uint32(v),
			}
		case uint16:
			msg.PropValue = &protomsg.SyncProp_Uint32Value{
				Uint32Value: uint32(v),
			}
		case uint32:
			msg.PropValue = &protomsg.SyncProp_Uint32Value{
				Uint32Value: v,
			}
		case uint64:
			msg.PropValue = &protomsg.SyncProp_Uint64Value{
				Uint64Value: uint64(v),
			}
		case string:
			msg.PropValue = &protomsg.SyncProp_StringValue{
				StringValue: v,
			}
		case float32:
			msg.PropValue = &protomsg.SyncProp_FloatValue{
				FloatValue: v,
			}
			// msg.PropValue.(*protomsg.SyncBaseInfo_FloatValue).FloatValue = float32(prop.value.(float32))
		case float64:
			msg.PropValue = &protomsg.SyncProp_DoubleValue{
				DoubleValue: v,
			}
		case msgdef.IMsg:
			d, _ := v.Marshal()
			msg.PropValue = &protomsg.SyncProp_Msg_Value{
				Msg_Value: d,
			}
		}
		result[i] = msg
	}
	return result
}
